#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <cstring>
#include <sys/wait.h>
#include <sys/types.h>
using namespace std;

#define COMMAND_SIZE  1024
#define FORMAT "[%s@%s %s]# "

#define MAXARGC 128
char* g_argv[MAXARGC];
int g_argc = 0;

//获取用户名
const char* GetUserName()
{
    const char* name = getenv("USER");
    return name == NULL ? "none" : name;
}

//
const char* GetHostName()
{
    const char* name = getenv("HOSTNAME");
    return name == NULL ? "none":name;
}


//获取路径
const char* GetPwd()
{
    const char* name = getenv("PWD");
    return name == NULL ? "none":name;
}

//只获取指令名称
string DirName(const char* pwd)
{
#define slash "/"
    string dir = pwd;
    if(dir == slash) return slash;
    auto pos = dir.rfind(slash);
    if(pos == string::npos)return "bug?";
    return dir.substr(pos+1);
    
}

//格式化命令行提示符，方便后期维护
void MakeCommandLine(char cmd_prompt[], int size)
{
   //snprintf(cmd_prompt,size,FORMAT,GetUserName(),GetHostName(),GetPwd());
     snprintf(cmd_prompt,size,FORMAT,GetUserName(),GetHostName(),DirName(GetPwd()).c_str());
}

//输出命题行提示符
void PrintCommandPrompt()
{
    char prompt[COMMAND_SIZE];
    MakeCommandLine(prompt,sizeof(prompt));
    printf("%s",prompt);
    fflush(stdout);                                                       
}
              
//获取用户输入命令
bool GetCommandLine(char* out,int size)
{
    char* c = fgets(out,size,stdin);
    if(c == NULL) return false;
    out[strlen(out)-1] = 0;
    if(strlen(out) == 0) return false;
    return true;
}

//命令行解释
bool CommandTransplate(char* commandline)
{
#define seg " "
    g_argc = 0;
    g_argv[g_argc++] = strtok(commandline,seg);
    while((bool)(g_argv[g_argc++] = strtok(NULL,seg)));
    g_argc--;
    return true;
}


//执行
int Execute()
{
    pid_t id = fork();
    if(id == 0)
    {
        execvp(g_argv[0],g_argv);
        exit(1);
    }   
    pid_t rid = waitpid(id,NULL,0);
    return 0;
}
int main()
{
    while(true)
    {
        //1.输出命令提示符
        PrintCommandPrompt();
    
        //2.获取用户输入命令
        char CommandLine[COMMAND_SIZE];
        if(!GetCommandLine(CommandLine,sizeof(CommandLine)))
            continue;
   
        //3.解析用户输入
        CommandTransplate(CommandLine);

        //4.执行
        Execute();
    }
    return 0;
}

